package com.tyun.modules.api.interceptor;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tyun.common.exception.UCException;
import com.tyun.modules.api.annotation.AuthIgnore;
import com.tyun.modules.sys.entity.SysUserToken;
import com.tyun.modules.sys.service.ISysUserTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author tao cong cong
 * @create 2018/2/17 下午4:09
 */
@Component()
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";

    @Autowired
    private ISysUserTokenService sysUserTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 验证有无注解
        AuthIgnore authIgnore;
        if (handler instanceof HandlerMethod) {
            authIgnore = ((HandlerMethod)handler).getMethodAnnotation(AuthIgnore.class);
        } else {
            return true;
        }
        if (authIgnore != null){
            return true;
        }
        // 业务处理,从header中获取token
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        // token不能为空
        if (StringUtils.isBlank(token)){
            throw new UCException("token不能为空");
        }
        SysUserToken sysUserToken = new SysUserToken();
        SysUserToken tokenEntity = sysUserTokenService.selectOne(new EntityWrapper<SysUserToken>(sysUserToken).eq("token",token));
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new UCException("token失效，请重新登录");
        }
        // 设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(LOGIN_USER_KEY, tokenEntity.getUserId());
        return true;
    }
}
